package king.dominic.jlibrary.view;


import android.app.Activity;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.StringRes;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import king.dominic.jlibrary.R;
import king.dominic.jlibrary.activity.OriginActivity;


/**
 * Created by king on 2017/2/17.
 * WindowUtil
 */
@SuppressWarnings("unused")
public class WindowUtil {
    private static final String TAG = "WindowUtil";
    public static int width = 0;
    public static int height = 0;
    private static int statusBarColor;

    private WindowUtil() {
    }

    public static void initWindowSize(AppCompatActivity activity) {
        if (width != 0 && height != 0) return;
        Point outSize = new Point();
        activity.getWindowManager().getDefaultDisplay().getSize(outSize);
        width = outSize.x;
        height = outSize.y;
    }

    public static void initWindow(AppCompatActivity activity) {
        hideAppCompatActivityActionBar(activity);
        translucentStatusBar(activity);
//        translucentNavigation(activity);
        initWindowSize(activity);
//        setNavigationBarColor(activity);
    }

    private static void setNavigationBarColor(AppCompatActivity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            activity.getWindow().setNavigationBarColor(getTitleBarColor(activity));
        }
    }

    public static void translucentNavigation(AppCompatActivity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
    }

    public static void translucentStatusBar(AppCompatActivity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

    /**
     * 获取系统定义的默认高度
     *
     * @param context
     * @return
     */
    public static int getStatusBarHeightDefault(Context context) {
        return getStatusBarHeight(context);
    }

    /**
     * 获取Activity中的系统的status bar 高度
     *
     * @param context
     * @return
     */
    public static int getStatusBarHeightInActivityBySystem(Context context) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT)
            return getStatusBarHeightDefault(context);
        final Activity activity = (Activity) context;
        final int f = activity.getWindow().getAttributes().flags | ~WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (f == 0xffffffff) return 0;
        return getStatusBarHeightDefault(context);
    }

    public static int getStatusBarHeight(Context context) {
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        return context.getResources().getDimensionPixelSize(resourceId);
    }

    public static int getStatusBarColor(Context context) {
        int resourceId = context.getResources().getIdentifier("colorPrimaryDark", "color", context.getPackageName());
        return ContextCompat.getColor(context, resourceId);
    }

    public static int getTitleBarColor(Context context) {
        int resourceId = context.getResources().getIdentifier("colorPrimary", "color", context.getPackageName());
        return ContextCompat.getColor(context, resourceId);
    }

    public static int getNavigationBarColor(Context context) {
        int resourceId = context.getResources().getIdentifier("colorPrimary", "color", context.getPackageName());
        return ContextCompat.getColor(context, resourceId);
    }

    public static int getNavigationBarHeight(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            Display display = activity.getWindowManager().getDefaultDisplay();
            Point size = new Point();
            Point realSize = new Point();
            display.getSize(size);
            display.getRealSize(realSize);
            return realSize.y - size.y;
        }

        boolean menu = ViewConfiguration.get(activity).hasPermanentMenuKey();
        boolean back = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK);
        if (!(menu || back))
            return getNavigationBarHeight((Context) activity);
        return 0;
    }

    private static int getNavigationBarHeight(Context context) {
        Resources resources = context.getResources();
        int navigationBarHeight = 0;
        int resIdShow = resources.getIdentifier("config_showNavigationBar", "bool", "android");
        boolean hasNavigationBar = false;
        if (resIdShow > 0) {
            hasNavigationBar = resources.getBoolean(resIdShow);//是否显示底部navigationBar
        }
        if (hasNavigationBar) {
            int resIdNavigationBar = resources.getIdentifier("navigation_bar_height", "dimen", "android");
            if (resIdNavigationBar > 0) {
                navigationBarHeight = resources.getDimensionPixelSize(resIdNavigationBar);//navigationBar高度
            }
        }
        return navigationBarHeight;
    }

    public static boolean isNavigationBarShow(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            Display display = activity.getWindowManager().getDefaultDisplay();
            Point size = new Point();
            Point realSize = new Point();
            display.getSize(size);
            display.getRealSize(realSize);
            return realSize.y != size.y;
        } else {
            boolean menu = ViewConfiguration.get(activity).hasPermanentMenuKey();
            boolean back = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK);
            return !(menu || back);
        }
    }

    public int getActionBarHeight(AppCompatActivity context) {
        int actionBarHeight = 0;
        if (context.getSupportActionBar() == null) return actionBarHeight;
        if ((actionBarHeight = context.getSupportActionBar().getHeight()) != 0) {
            return actionBarHeight;
        }
        final TypedValue tv = new TypedValue();
        if (context.getTheme().resolveAttribute(android.support.v7.appcompat.R.attr.actionBarSize, tv, true)) {
            actionBarHeight = TypedValue.complexToDimensionPixelSize(
                    tv.data, context.getResources().getDisplayMetrics());
        }
        return actionBarHeight;
    }

    private static void hideAppCompatActivityActionBar(AppCompatActivity context) {
        ActionBar bar = context.getSupportActionBar();
        if (bar != null) bar.hide();
    }

    public static void hideStatusBar(AppCompatActivity context) {
        underStatusBar(context);
    }

    public static void hideTitleBar(AppCompatActivity context) {
        View titleBar = context.findViewById(R.id.titleBar);
        if (titleBar != null)
            titleBar.setVisibility(View.GONE);
    }

    /**
     * 如果要隐藏status bar 必须先调用hideStatusBar
     * @param context AppCompatActivity
     */
    public static void underTitleBar(AppCompatActivity context) {
        View titleBar = context.findViewById(R.id.titleBar);
        View contentGroup = context.findViewById(R.id.content_group);
        View statusBar = context.findViewById(R.id.statusBar);
        if (titleBar != null && contentGroup != null && statusBar != null) {
            titleBar.setBackgroundColor(Color.TRANSPARENT);
            RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) contentGroup.getLayoutParams();
            lp.removeRule(RelativeLayout.BELOW);
            lp.addRule(RelativeLayout.BELOW, R.id.statusBar);
            if (statusBar.getLayoutParams().height == 0 || statusBar.getVisibility() == View.GONE) {
                ((RelativeLayout.LayoutParams) titleBar.getLayoutParams()).topMargin = getStatusBarHeightDefault(context);
            }
            context.findViewById(R.id.view_util_content).requestLayout();
        }
    }

    public static void fullScreenNow(AppCompatActivity context) {
        int flags;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
            flags = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE
                    | View.SYSTEM_UI_FLAG_FULLSCREEN;
        else
            flags = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
        context.getWindow().getDecorView().setSystemUiVisibility(flags);
        hideTitleBar(context);
        underStatusBar(context);
        underNavigationBar(context);
    }

    public static void underStatusBar(AppCompatActivity activity) {
        View statusBar = activity.findViewById(R.id.statusBar);
        statusBar.setVisibility(View.GONE);
    }

    public static void underNavigationBar(AppCompatActivity activity) {
        View androidNavigationBar = activity.findViewById(R.id.androidNavigationBar);
        androidNavigationBar.setVisibility(View.GONE);
    }

    public static void showStatusBar(AppCompatActivity activity) {
        View titleBar = activity.findViewById(R.id.statusBar);
        titleBar.setVisibility(View.VISIBLE);
    }

    public static void showTitleBar(AppCompatActivity context) {
        View titleBar = context.findViewById(R.id.titleBar);
        if (titleBar != null)
            titleBar.setVisibility(View.VISIBLE);
    }

    public static ViewGroup getViewRoot(AppCompatActivity a) {
        return (ViewGroup) a.findViewById(android.R.id.content);
    }

    /**
     * @hide
     */
    public static View setContentView(WindowAttribute attribute) {
        attribute.window = LayoutInflater.from(attribute.activity).inflate(WindowAttribute.DEFAULT_LAYOUT_ID, null);
        FrameLayout frameLayout = (FrameLayout) attribute.window.findViewById(R.id.content_group);
        frameLayout.removeAllViews();

        if (attribute.contentView == null)
            attribute.contentView = LayoutInflater.from(attribute.activity).inflate(attribute.contentLayoutResourceId, null);

        View statusBar = attribute.window.findViewById(R.id.statusBar);
        statusBar.getLayoutParams().height = attribute.statusBarAttribute.height;
        statusBar.setBackground(attribute.statusBarAttribute.background);
        if (attribute.statusBarAttribute.showBlack) setStatusBarContentDark(attribute.activity);
        if (!attribute.navigationBarAttribute.showDefault) {
            translucentNavigation(attribute.activity);
            View navigationBar = attribute.window.findViewById(R.id.androidNavigationBar);
            navigationBar.getLayoutParams().height = attribute.navigationBarAttribute.height;
            navigationBar.setBackgroundColor(attribute.navigationBarAttribute.background);
        }

        frameLayout.addView(attribute.contentView);

        //attribute.activity.setContentView(content);

        setTitleBar(attribute.titleBarAttribute);

        setBottomLine(attribute);

        return attribute.window;
    }

    public static void showDefaultTitleBar(OriginActivity activity) {
        setTitleBar(activity.getWindowAttribute().titleBarAttribute);
    }

    private static void setTitleBar(TitleBarAttribute attribute) {
        FrameLayout titleBar = (FrameLayout) attribute.windowAttribute.window.findViewById(R.id.titleBar);
        if (attribute.hide) {
            titleBar.setVisibility(View.GONE);
            return;
        }
        titleBar.setBackground(attribute.background);
        titleBar.removeAllViews();
        View view = LayoutInflater.from(attribute.windowAttribute.activity).inflate(attribute.layoutResourceId, titleBar);
        ArrayList<TitleBarAttribute.Action> left = attribute.left;
        ArrayList<TitleBarAttribute.Action> right = attribute.right;
        setLeft(view, left);
        setRight(view, right);
        setCenter(view, attribute.centerTextAttribute);
    }

    private static void setCenter(View view, TextAttribute attribute) {
        if (attribute.custom != null) {
            FrameLayout center = (FrameLayout) view.findViewById(R.id.center);
            center.removeAllViews();
            center.addView(attribute.custom);
            return;
        }
        TextView textView = (TextView) view.findViewById(R.id.title_in_title_bar);
        textView.setText(attribute.text);
        textView.setTextSize(attribute.size);
        textView.setTextColor(attribute.color);
    }

    private static void setActions(Context context, ViewGroup contentView, List<TitleBarAttribute.Action> actions) {
        contentView.removeAllViews();
        for (TitleBarAttribute.Action action : actions) {
            addAction(context, contentView, action);
        }
    }

    private static void addAction(Context context, ViewGroup contentView, TitleBarAttribute.Action action) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_action, contentView, false);
        notifyAction(context, view, action);
        contentView.addView(view);
    }

    private static void notifyAction(Context context, View view, TitleBarAttribute.Action action) {
        if (context == null || view == null || action == null) return;

        View.OnClickListener click = action.click();

        view.setOnClickListener(click);
        view.setTag(action);

        notifyActionIcon(context, view, action);
        notifyActionText(context, view, action);
        notifyActionPoint(context, view, action.point());
    }

    private static void notifyActionText(Context context, View view, TitleBarAttribute.Action action) {
        TextView actionText = (TextView) view.findViewById(R.id.action_text);

        CharSequence text = action.text();
        ColorStateList textColor = action.textColor();
        float size = action.size_dp();
        Drawable background = action.background();

        if (TextUtils.isEmpty(text)) {
            actionText.setVisibility(View.GONE);
            return;
        } else {
            actionText.setVisibility(View.VISIBLE);
        }

        int padding = dip2px(context, 10);

        actionText.setText(text);
        actionText.setTextColor(textColor);
        actionText.setTextSize(size);
        actionText.setPadding(padding, 0, padding, 0);
        actionText.setBackground(background);
    }

    private static void notifyActionIcon(Context context, View view, TitleBarAttribute.Action action) {
        ImageView actionIcon = (ImageView) view.findViewById(R.id.action_icon);

        Drawable src = action.src();
        Drawable background = action.background();
        int imgResId = action.imgResId();
        int backgroundResId = action.backgroundResId();

        int size = dip2px(context, action.size_dp());

        if (src == null && imgResId == -1) {
            actionIcon.setVisibility(View.GONE);
            return;
        } else {
            actionIcon.setVisibility(View.VISIBLE);
        }

        int height = dip2px(context, WindowAttribute.TITLE_BAR_DEFAULT_HEIGHT);
        int width = dip2px(context, WindowAttribute.TITLE_BAR_DEFAULT_HEIGHT - 10);
        int padding = (height - size) / 2;
        int padding2 = (width - size) / 2;

        actionIcon.setPadding(padding2, padding, padding2, padding);
        if (src != null)
            actionIcon.setImageDrawable(src);
        if (imgResId != -1)
            actionIcon.setImageResource(imgResId);
        if (background != null)
            actionIcon.setBackground(background);
        if (backgroundResId != -1)
            actionIcon.setBackgroundResource(backgroundResId);
        ViewGroup.LayoutParams lp = actionIcon.getLayoutParams();
        lp.width = width;
        lp.height = height;

        actionIcon.requestLayout();
    }

    private static void notifyActionPoint(Context context, View view, TitleBarAttribute.ActionPoint point) {
        if (point == null) return;

        TextView actionPoint = (TextView) view.findViewById(R.id.action_point);

        final boolean isShowNumber = point.isShowNumber;
        final float pointSize = point.pointSize == 0 ? (isShowNumber ? 17 : 8) : point.pointSize;
        final float textSize = point.textSize == 0 ? 12 : point.textSize;
        final int count = point.count;
        final int maxCount = point.maxCount;
        final Drawable background = point.background;

        if (background != null) {
            actionPoint.setBackground(background);
        }

        if (count > 0) {
            actionPoint.setVisibility(View.VISIBLE);
        } else {
            actionPoint.setVisibility(View.GONE);
            return;
        }

        actionPoint.setTextSize(textSize);
        actionPoint.setGravity(Gravity.CENTER);
        ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) actionPoint.getLayoutParams();
        lp.width = lp.height = dip2px(context, pointSize);

        lp.leftMargin = dip2px(context, point.left);
        lp.topMargin = dip2px(context, point.top + 6);
        lp.rightMargin = dip2px(context, point.right + 3);
        lp.bottomMargin = dip2px(context, point.bottom);

        if (isShowNumber) {
            actionPoint.setText(String.valueOf(count > maxCount ? maxCount : count));
        }

        actionPoint.requestLayout();
    }

    private static void setRight(View view, ArrayList<TitleBarAttribute.Action> right) {
        if (right == null || right.isEmpty()) return;
        final Context context = view.getContext();
        LinearLayout contentView = (LinearLayout) view.findViewById(R.id.right);
        setActions(context, contentView, right);
    }

    private static void setLeft(View view, ArrayList<TitleBarAttribute.Action> left) {
        if (left == null || left.isEmpty()) return;
        final Context context = view.getContext();
        LinearLayout contentView = (LinearLayout) view.findViewById(R.id.left);
        setActions(context, contentView, left);
    }

    public static void setTitle(@NonNull WindowAttribute attribute, @StringRes int titleId) {
        setTitle(attribute, attribute.activity.getString(titleId));
    }

    public static void setTitle(@NonNull WindowAttribute attribute, CharSequence title) {
        attribute.titleBarAttribute.centerTextAttribute.setText(title);
        if (attribute.initContentView) {
            TextView text = (TextView) attribute.window.findViewById(R.id.title_in_title_bar);
            if (text == null) {
                showDefaultTitleBar((OriginActivity) attribute.activity);
            } else {
                text.setText(title);
            }
        }
    }

    public static void addLeftAction(@NonNull WindowAttribute attribute, TitleBarAttribute.Action action) {
        attribute.titleBarAttribute.addLeft(action);
        if (attribute.initContentView) {
            LinearLayout contentView = (LinearLayout) attribute.window.findViewById(R.id.left);
            addAction(attribute.activity, contentView, action);
        }
    }

    public static void addRightAction(@NonNull WindowAttribute attribute, TitleBarAttribute.Action action) {
        attribute.titleBarAttribute.addRight(action);
        if (attribute.initContentView) {
            LinearLayout contentView = (LinearLayout) attribute.window.findViewById(R.id.right);
            addAction(attribute.activity, contentView, action);
        }
    }

    public static void removeLeftAction(@NonNull WindowAttribute attribute, TitleBarAttribute.Action action) {
        attribute.titleBarAttribute.removeLeft(action);
        if (attribute.initContentView) {
            LinearLayout contentView = (LinearLayout) attribute.window.findViewById(R.id.left);
            removeAction(contentView, action);
        }
    }

    public static void removeRightAction(@NonNull WindowAttribute attribute, TitleBarAttribute.Action action) {
        attribute.titleBarAttribute.removeRight(action);
        if (attribute.initContentView) {
            LinearLayout contentView = (LinearLayout) attribute.window.findViewById(R.id.right);
            removeAction(contentView, action);
        }
    }

    public static void removeAllLeftAction(@NonNull WindowAttribute attribute) {
        attribute.titleBarAttribute.removeAllLeft();
        if (attribute.initContentView) {
            LinearLayout contentView = (LinearLayout) attribute.window.findViewById(R.id.left);
            contentView.removeAllViews();
        }
    }

    public static void removeAllRightAction(@NonNull WindowAttribute attribute) {
        attribute.titleBarAttribute.removeAllRight();
        if (attribute.initContentView) {
            LinearLayout contentView = (LinearLayout) attribute.window.findViewById(R.id.right);
            contentView.removeAllViews();
        }
    }

    public static void setCustomCenter(@NonNull WindowAttribute attribute, View view) {
        attribute.titleBarAttribute.centerTextAttribute.custom = view;
        if (attribute.initContentView) {
            FrameLayout linearLayout = (FrameLayout) attribute.window.findViewById(R.id.center);
            linearLayout.removeAllViews();
            linearLayout.addView(view);
        }
    }

    public static void notifyRightAction(@NonNull WindowAttribute attribute, TitleBarAttribute.Action action) {
        if (attribute.initContentView && attribute.titleBarAttribute.containsRightAction(action)) {
            LinearLayout contentView = (LinearLayout) attribute.window.findViewById(R.id.right);
            View actionView = findActionView(contentView, action);
            notifyAction(attribute.activity, actionView, action);
        }
    }

    private static void removeAction(LinearLayout contentView, TitleBarAttribute.Action action) {
        View actionView = findActionView(contentView, action);
        if (actionView != null) contentView.removeView(actionView);
    }


    private static View findActionView(LinearLayout contentView, TitleBarAttribute.Action action) {
        int count = contentView.getChildCount();
        for (int i = 0; i < count; i++) {
            View child = contentView.getChildAt(i);
            if (action.equals(child.getTag())) {
                return child;
            }
        }
        return null;
    }

    public static int getNavigationBarAttributeHeight(OriginActivity activity) {
        NavigationBarAttribute navigationBarAttribute = activity.getWindowAttribute().navigationBarAttribute;
        return navigationBarAttribute.showDefault ? 0 : navigationBarAttribute.height;
    }

    private static void setBottomLine(WindowAttribute attribute) {
        if (attribute.titleBarAttribute.showBottomLine) {
            View line =  attribute.window.findViewById(R.id.titleBarLine);
            line.setBackgroundColor(attribute.titleBarAttribute.bottomLineColor);
            line.getLayoutParams().height = attribute.titleBarAttribute.bottomLineHeightPx;
            line.requestLayout();
        }
    }

    public static void setBottomLineColor(WindowAttribute attribute, int color) {
        attribute.getTitleBarAttribute().showBottomLine = true;
        attribute.getTitleBarAttribute().bottomLineColor = color;
        if (attribute.initContentView) {
            setBottomLine(attribute);
        }
    }

    public static void setBottomLineHeight(WindowAttribute attribute, int height) {
        attribute.getTitleBarAttribute().showBottomLine = true;
        attribute.getTitleBarAttribute().bottomLineHeightPx = height;
        if (attribute.initContentView) {
            setBottomLine(attribute);
        }
    }


    public static class WindowAttribute {
        private static final float TEXT_DEFAULT_SIZE = 20;
        private static final int TEXT_DEFAULT_COLOR = Color.WHITE;
        private static final int BOTTOM_LINE_DEFAULT_COLOR = Color.LTGRAY;
        private static final int TITLE_BAR_DEFAULT_HEIGHT = 50;
        private static final int DEFAULT_LAYOUT_ID = R.layout.layout_linearlayout_content;
        private static int TEXT_ACTION_DEFAULT_COLOR = Color.WHITE;
        private static float TEXT_ACTION_DEFAULT_SIZE = 14;
        private final AppCompatActivity activity;
        private StatusBarAttribute statusBarAttribute;
        private TitleBarAttribute titleBarAttribute;
        private NavigationBarAttribute navigationBarAttribute;
        public int contentLayoutResourceId;
        public boolean initContentView = false;
        public View contentView;
        private View window;

        public static void setTextActionDefaultColor(int color) {
            TEXT_ACTION_DEFAULT_COLOR = color;
        }

        public static void setTextActionDefaultSize(float size) {
            TEXT_ACTION_DEFAULT_SIZE = size;
        }

        public WindowAttribute(AppCompatActivity activity, @LayoutRes int contentLayoutResourceId) {
            this(activity);
            this.contentLayoutResourceId = contentLayoutResourceId;
        }

        public WindowAttribute(AppCompatActivity activity) {
            this.activity = activity;
            this.statusBarAttribute = new StatusBarAttribute(this);
            this.titleBarAttribute = new TitleBarAttribute(this);
            this.navigationBarAttribute = new NavigationBarAttribute(this);
        }

        public StatusBarAttribute getStatusBarAttribute() {
            return statusBarAttribute;
        }

        public void setStatusBarAttribute(@NonNull StatusBarAttribute statusBarAttribute) {
            this.statusBarAttribute = statusBarAttribute;
        }

        public TitleBarAttribute getTitleBarAttribute() {
            return titleBarAttribute;
        }

        public void setTitleBarAttribute(@NonNull TitleBarAttribute titleBarAttribute) {
            this.titleBarAttribute = titleBarAttribute;
        }

        public NavigationBarAttribute getNavigationBarAttribute() {
            return navigationBarAttribute;
        }

        public void setNavigationBarAttribute(@NonNull NavigationBarAttribute navigationBarAttribute) {
            this.navigationBarAttribute = navigationBarAttribute;
        }

        public int getContentLayoutResourceId() {
            return contentLayoutResourceId;
        }

        public void setContentLayoutResourceId(int contentLayoutResourceId) {
            this.contentLayoutResourceId = contentLayoutResourceId;
        }

        public TitleBarAttribute createTitleBarAttribute() {
            return new TitleBarAttribute(this);
        }
    }

    public static class StatusBarAttribute {
        private final WindowAttribute windowAttribute;

        private StatusBarAttribute(WindowAttribute windowAttribute) {
            this.windowAttribute = windowAttribute;
            background = new ColorDrawable(getStatusBarColor(windowAttribute.activity));
            height = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT ? getStatusBarHeight(windowAttribute.activity) : 0;
        }

        public boolean showBlack = false;
        public boolean overLayout = false;
        public Drawable background;
        public int height;
    }

    public static class TitleBarAttribute {
        private final WindowAttribute windowAttribute;
        public int layoutResourceId;
        private TextAttribute centerTextAttribute;

        private TitleBarAttribute(WindowAttribute windowAttribute) {
            this.windowAttribute = windowAttribute;
            background = new ColorDrawable(getTitleBarColor(windowAttribute.activity));
            layoutResourceId = R.layout.item_title_bar;
            centerTextAttribute = new TextAttribute();
        }

        public Drawable background;
        public boolean overLayout = false;
        public boolean useDefault = false;
        public boolean hide = false;
        public boolean showBottomLine = false;
        public int bottomLineColor = WindowAttribute.BOTTOM_LINE_DEFAULT_COLOR;
        public int bottomLineHeightPx = 1;
        public int height = WindowAttribute.TITLE_BAR_DEFAULT_HEIGHT;

        private ArrayList<Action> left;
        private ArrayList<Action> right;

        public TextAttribute getCenterTextAttribute() {
            return centerTextAttribute;
        }

        public void setCenterTextAttribute(TextAttribute centerTextAttribute) {
            this.centerTextAttribute = centerTextAttribute;
        }

        private void addLeft(Action action) {
            if (left == null) left = new ArrayList<>();
            left.add(action);
        }

        private boolean removeLeft(Action action) {
            return !(left == null || left.isEmpty() || action == null) && left.remove(action);
        }

        private boolean removeRight(Action action) {
            return !(right == null || right.isEmpty() || action == null) && right.remove(action);
        }

        private void addRight(Action action) {
            if (right == null) right = new ArrayList<>();
            right.add(action);
        }

        private void removeAllLeft() {
            if (left != null) left.clear();
        }

        private void removeAllRight() {
            if (right != null) right.clear();
        }

        private boolean containsRightAction(Action action) {
            return right != null && right.contains(action);
        }

        public static class ActionPoint {
            public boolean isShowNumber;
            public int maxCount;
            public int count;
            public float pointSize;
            public float textSize;
            public float left;
            public float top;
            public float right;
            public float bottom;

            public Drawable background;

            private ActionPoint(Builder builder) {
                isShowNumber = builder.isShowNumber;
                maxCount = builder.maxCount;
                count = builder.count;
                pointSize = builder.pointSize;
                textSize = builder.textSize;
                left = builder.left;
                top = builder.top;
                right = builder.right;
                bottom = builder.bottom;
                background = builder.background;
            }

            public static final class Builder {
                private boolean isShowNumber = true;
                private int maxCount = 99;
                private int count = 0;
                private float pointSize = 0;
                private float textSize = 0;
                private float left = 0;
                private float top = 0;
                private float right = 0;
                private float bottom = 0;
                private Drawable background;

                public Builder() {
                }

                public Builder isShowNumber(boolean val) {
                    isShowNumber = val;
                    return this;
                }

                public Builder maxCount(int val) {
                    maxCount = val;
                    return this;
                }

                public Builder count(int val) {
                    count = val;
                    return this;
                }

                public Builder pointSize(float val) {
                    pointSize = val;
                    return this;
                }

                public Builder textSize(float val) {
                    textSize = val;
                    return this;
                }

                public Builder left(float val) {
                    left = val;
                    return this;
                }

                public Builder top(float val) {
                    top = val;
                    return this;
                }

                public Builder right(float val) {
                    right = val;
                    return this;
                }

                public Builder bottom(float val) {
                    bottom = val;
                    return this;
                }

                public Builder background(Drawable val) {
                    background = val;
                    return this;
                }

                public ActionPoint build() {
                    return new ActionPoint(this);
                }
            }
        }

        public interface Action {

            CharSequence text();

            Drawable src();

            Drawable background();

            int imgResId();

            int backgroundResId();

            ColorStateList textColor();

            float size_dp();

            View.OnClickListener click();

            ActionPoint point();

        }

        public static abstract class TextAction implements Action {

            public int imgResId() {
                return -1;
            }

            public int backgroundResId() {
                return -1;
            }

            @Override
            public Drawable src() {
                return null;
            }

            @Override
            public Drawable background() {
                return null;
            }

            @Override
            public ColorStateList textColor() {
                return ColorStateList.valueOf(WindowAttribute.TEXT_ACTION_DEFAULT_COLOR);
            }

            @Override
            public float size_dp() {
                return WindowAttribute.TEXT_ACTION_DEFAULT_SIZE;
            }

            @Override
            public ActionPoint point() {
                return null;
            }
        }

        public static abstract class ImageAction implements Action {

            public int imgResId() {
                return -1;
            }

            public int backgroundResId() {
                return -1;
            }

            @Override
            public CharSequence text() {
                return null;
            }

            @Override
            public ColorStateList textColor() {
                return null;
            }

            @Override
            public Drawable background() {
                return null;
            }

            @Override
            public float size_dp() {
                return WindowAttribute.TITLE_BAR_DEFAULT_HEIGHT;
            }

            @Override
            public ActionPoint point() {
                return null;
            }
        }
    }

    public static class NavigationBarAttribute {
        private final WindowAttribute windowAttribute;
        private int background;
        public int height;
        public boolean showDefault = true;

        private NavigationBarAttribute(WindowAttribute windowAttribute) {
            this.windowAttribute = windowAttribute;
            height = getNavigationBarHeight(windowAttribute.activity);
            background = getNavigationBarColor(windowAttribute.activity);
        }
    }

    public static class TextAttribute {
        CharSequence text;
        ColorStateList color;
        float size;
        public View custom;

        public TextAttribute() {
            text = "标题";
            color = ColorStateList.valueOf(WindowAttribute.TEXT_DEFAULT_COLOR);
            size = WindowAttribute.TEXT_DEFAULT_SIZE;
        }

        public CharSequence getText() {
            return text;
        }

        public void setText(CharSequence text) {
            this.text = text;
        }

        public ColorStateList getColor() {
            return color;
        }

        public void setColor(ColorStateList color) {
            this.color = color;
        }

        public void setColor(int color) {
            this.color = ColorStateList.valueOf(color);
        }

        public float getSize() {
            return size;
        }

        public void setSize(float size) {
            this.size = size;
        }
    }

    public static View setCustomTitleBar(AppCompatActivity activity, @LayoutRes int resId) {
        FrameLayout titleBar = (FrameLayout) activity.findViewById(R.id.titleBar);
//        titleBar.setBackgroundColor(getTitleBarColor(activity));
        titleBar.removeAllViews();
        return LayoutInflater.from(activity).inflate(resId, titleBar);
    }

    public static View setCustomTitleBar(AppCompatActivity activity, View bar) {
        FrameLayout titleBar = (FrameLayout) activity.findViewById(R.id.titleBar);
//        titleBar.setBackgroundColor(getTitleBarColor(activity));
        titleBar.removeAllViews();
        titleBar.addView(bar);
        ViewGroup.LayoutParams lp = bar.getLayoutParams();
        lp.width = ViewGroup.LayoutParams.MATCH_PARENT;
        lp.height = ViewGroup.LayoutParams.MATCH_PARENT;
        bar.requestLayout();
        return bar;
    }

    public static View getViewUtilContent(AppCompatActivity activity) {
        return activity.findViewById(R.id.view_util_content);
    }

    public static View getTitleBar(AppCompatActivity activity) {
        return activity.findViewById(R.id.titleBar);
    }

    public static void setTitleBarAlpha(AppCompatActivity activity, float alpha) {
        getTitleBar(activity).setAlpha(alpha);
    }

    public static void setStatusBarAlpha(AppCompatActivity activity, float alpha) {
        getStatusBar(activity).setAlpha(alpha);
    }

    public static void setNavigationBarAlpha(AppCompatActivity activity, float alpha) {
        getNavigationBar(activity).setAlpha(alpha);
    }

    public static View getStatusBar(AppCompatActivity activity) {
        return activity.findViewById(R.id.statusBar);
    }

    public static View getNavigationBar(AppCompatActivity activity) {
        return activity.findViewById(R.id.androidNavigationBar);
    }

    public static void setStatusBarColor(AppCompatActivity activity, int color) {
        getStatusBar(activity).setBackgroundColor(color);
    }

    public static void setTitleBarColor(AppCompatActivity activity, int color) {
        getTitleBar(activity).setBackgroundColor(color);
    }

    public static void setTitleBarBackground(AppCompatActivity activity, Drawable drawable) {
        getTitleBar(activity).setBackground(drawable);
    }

    public static void setNavigationBarColor(AppCompatActivity activity, int color) {
        getNavigationBar(activity).setBackgroundColor(color);
    }

    public static void setStatusBarContentDark(AppCompatActivity activity) {
        StatusBarLightMode(activity);
    }

    public static void setStatusBarContentDark(Window window) {
        StatusBarLightMode(window);
    }

    /**
     * 设置状态栏黑色字体图标，
     * 适配4.4以上版本MIUIV、Flyme和6.0以上版本其他Android
     *
     * @return 1:MIUUI 2:Flyme 3:android6.0
     */
    private static int StatusBarLightMode(Window window) {
        int result = 0;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (MIUISetStatusBarLightMode(window, true) && Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                result = 1;
            } else if (FlymeSetStatusBarLightMode(window, true)) {
                result = 2;
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
                result = 3;
            }
        }
        return result;
    }

    /**
     * 设置状态栏黑色字体图标，
     * 适配4.4以上版本MIUIV、Flyme和6.0以上版本其他Android
     *
     * @param activity activity
     * @return 1:MIUUI 2:Flyme 3:android6.0
     */
    private static int StatusBarLightMode(AppCompatActivity activity) {
        return StatusBarLightMode(activity.getWindow());
    }

    /**
     * 设置状态栏图标为深色和魅族特定的文字风格
     * 可以用来判断是否为Flyme用户
     *
     * @param window 需要设置的窗口
     * @param dark   是否把状态栏字体及图标颜色设置为深色
     * @return boolean 成功执行返回true
     */
    private static boolean FlymeSetStatusBarLightMode(Window window, boolean dark) {
        boolean result = false;
        if (window != null) {
            try {
                WindowManager.LayoutParams lp = window.getAttributes();
                Field darkFlag = WindowManager.LayoutParams.class
                        .getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
                Field meizuFlags = WindowManager.LayoutParams.class
                        .getDeclaredField("meizuFlags");
                darkFlag.setAccessible(true);
                meizuFlags.setAccessible(true);
                int bit = darkFlag.getInt(null);
                int value = meizuFlags.getInt(lp);
                if (dark) {
                    value |= bit;
                } else {
                    value &= ~bit;
                }
                meizuFlags.setInt(lp, value);
                window.setAttributes(lp);
                result = true;
            } catch (Exception e) {
                //LogUtil.e("BaseActivity", "FlymeSetStatusBarLightMode: 设置状态栏图标为深色和魅族特定的文字风格", e);
            }
        }
        return result;
    }

    /**
     * 设置状态栏字体图标为深色，需要MIUIV6以上
     *
     * @param window 需要设置的窗口
     * @param dark   是否把状态栏字体及图标颜色设置为深色
     * @return boolean 成功执行返回true
     */
    private static boolean MIUISetStatusBarLightMode(Window window, boolean dark) {
        boolean result = false;
        if (window != null) {
            Class<? extends Window> clazz = window.getClass();
            try {
                int darkModeFlag;
                Class layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
                Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
                darkModeFlag = field.getInt(layoutParams);
                Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
                if (dark) {
                    extraFlagField.invoke(window, darkModeFlag, darkModeFlag);//状态栏透明且黑色字体
                } else {
                    extraFlagField.invoke(window, 0, darkModeFlag);//清除黑色字体
                }
                result = true;
            } catch (Exception e) {
                //LogUtil.e("BaseActivity", "MIUISetStatusBarLightMode: 设置状态栏字体图标为深色，需要MU6以上", e);
            }
        }
        return result;
    }

    public static FrameLayout getContentView(AppCompatActivity activity) {
        return (FrameLayout) activity.findViewById(R.id.content_group);
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static int getResourceId(Context context, String name, String defType, boolean androidValue) {
        final String packageName = androidValue ? "android" : context.getPackageName();
        return context.getResources().getIdentifier(name, defType, packageName);
    }

    public static int getAppColorId(Context context, String name) {
        return getResourceId(context, name, "color", false);
    }

    public static int getAppDrawableId(Context context, String name) {
        return getResourceId(context, name, "drawable", false);
    }

    public static int getAppMipmapId(Context context, String name) {
        return getResourceId(context, name, "mipmap", false);
    }

    //关闭软键盘
    public static void closeSoftKeyboard(Activity activity) {
        if (activity == null) return;
        View view = activity.getWindow().peekDecorView();
        if (view != null) {
            InputMethodManager inputManger = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
            if (inputManger != null) {
                inputManger.hideSoftInputFromWindow(view.getWindowToken(), 0);
            }
        }
    }

    //打开软键盘
    public static void showSoftKeyboard(EditText editText) {
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
        InputMethodManager inputManager = (InputMethodManager) editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputManager != null) {
            inputManager.showSoftInput(editText, 0);
        }
    }

    public static int getUIHeight(OriginActivity activity) {
        final WindowAttribute window = activity.getWindowAttribute();
        return height
                - (window.statusBarAttribute.overLayout ? 0 : getStatusBarHeight(activity))
                - (window.titleBarAttribute.useDefault ?
                (activity.getActionBar() == null ? 0 : activity.getActionBar().getHeight()) :
                dip2px(activity, window.titleBarAttribute.overLayout || window.titleBarAttribute.hide ? 0 : window.titleBarAttribute.height))
                - getNavigationBarAttributeHeight(activity);
    }
}
